package com.wxp.serviceImpl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.models.constant.JafCoreConstant;
import com.modules.utils.BeanUtils;
import com.wxp.dao.UnitDao;
import com.wxp.entity.Unit;
import com.wxp.service.UnitService;



/**
* Created by lewis on 2018-3-1 10:05:01.
*/
@Service
@Transactional
public class UnitServiceImpl implements UnitService {
    private static Logger logger	= LoggerFactory.getLogger(UnitServiceImpl.class);

   @Autowired
    private UnitDao unitDao;

    public Page<Unit> findAll(Pageable pageable){

        return this.unitDao.findAll(pageable);
    }
    public Page<Unit> findAll(Specification<Unit> spec,PageRequest pageRequest){
        return this.unitDao.findAll(spec,pageRequest);
    }
    
    @Transactional(readOnly = true)
	public Unit get(java.lang.String unitCode) {
		return this.unitDao.findOne(unitCode);
	}
    
    @Transactional(readOnly = true)
	public List<Unit> findAll() {
		return this.unitDao.findAll();
	}
    
    @Transactional(readOnly = true)
   	public List<Unit> findAll(Specification<Unit> spec) {
   		return this.unitDao.findAll(spec);
   	}
    
    public List<Unit> findAll(Specification<Unit> spec, Sort sort) {
		return this.unitDao.findAll(spec,sort);
	}
    
    
   
    
	public String saveUnit(Unit unit) {
		String result = null;
		if(StringUtils.isNotBlank(unit.getAdd())&&unit.getAdd().equals("1")) {
			//获取其父节点
			Unit parentUnit =  unitDao.findOne(unit.getParentCode());
			unit.setLevel(parentUnit.getLevel()+"."+unit.getUnitCode()+".");
			unit.setAdd("2");
			this.unitDao.save(unit);
			result = JafCoreConstant.SAVE_SUCCESS;
		}else {
			Unit existed = get(unit.getUnitCode());
			if ((existed.getVersion() != null) && (existed.getVersion().intValue() != unit.getVersion().intValue())){
				result = JafCoreConstant.OUT_OF_DATE;//已经被别人编辑更新过了
			}else {
				String[] properties = new String[] {"unitCode","unitName","level","parentCode",
				};
				BeanUtils.copyAssignProperties(unit, existed, properties);
				this.unitDao.save(existed);
				result = JafCoreConstant.UPDATE_SUCCESS;
			}
		}
		return result;
	}
	
	public void deleteUnit(Unit unit) {
		this.unitDao.delete(unit);
		
	}

	
	public void deleteUnit(java.lang.String unitCode) {
		this.unitDao.delete(unitCode);
	}

}
